<template>
	<view>
		<radio-group ref="radioList" v-model="selectedAddressIndex" @change="selectAddress" class="addressList">
			<view v-for="(item,index) in addressList" :key="index">
				<Address :item="item" :origin="type == 2 ? 3 : 1" />
				<radio v-if="type == 2" :value="index" class="radio" name="address"
					:checked="index == selectedAddressIndex" />
			</view>
		</radio-group>
		<button class="confirmBtn" @click="confirm" v-if="type == 2">确认</button>
		<button class="addBtn" @click="add">新增地址</button>
	</view>
</template>

<script>
	import Address from '@/components/Address.vue'
	import {
		nextTick
	} from "vue"
	export default {
		components: {
			Address
		},
		data() {
			return {
				addressList: [],
				type: 1,
				selectedAddressIndex: null,
				selectedAddressId: null
			}
		},
		onShow() {
			this.getAddressList()

		},
		onLoad(data) {
			if (data) {
				//从商品详情也跳转过来的
				this.type = data.type
				this.selectedAddressId = data.id
			}
		},
		methods: {
			selectAddress(event) {
				this.selectedAddressIndex = event.detail.value
				console.log(this.selectedAddressIndex)
			},
			async getAddressList() {
				uni.showLoading()
				const res = await this.$myRequest({
					url: 'user/applet/getUserAddressList'
				})
				if (res && res.code === 0) {
					this.addressList = res.data
					uni.hideLoading()
					if (this.selectedAddressId) {
						//获取的选中地址的id并得出索引，传给Address
						this.addressList.forEach((item, index) => {
							console.log(this.selectedAdressId)
							if (item.id == this.selectedAddressId) {
								this.selectedAddressIndex = index
								return;
							}
						})
					}
				}
			},
			add() {
				uni.navigateTo({
					url: '/pages/addressForm/addressForm'
				})
			},
			//确认选中地址
			confirm() {
				console.log(this.selectedAddressIndex)
				if (!this.selectedAddressIndex) {
					uni.showToast({
						title: '还没有选择地址',
						icon: 'none',
						duration: 2000
					})
				} else {
					let pages = getCurrentPages();
					let prevPage = pages[pages.length - 2];
					prevPage.$vm.address = this.addressList[this.selectedAddressIndex];
					uni.navigateBack({
						delta: 1
					})
				}
			}
		}
	}
</script>


<style lang="scss">
	@import '@/static/iconfont/iconfont.css';

	page {
		background-color: #F8F8F8;
	}

	.addressList {
		width: 700rpx;
		background-color: white;
		border-radius: 10px;
		margin: 25rpx;
	}

	.addBtn {
		position: fixed;
		bottom: 20rpx;
		width: 350rpx;
		height: 100rpx;
		background-color: #FFB300;
		color: white;
		margin: 0 200rpx 0 200rpx;
	}

	.confirmBtn {
		width: 350rpx;
		height: 100rpx;
		background-color: #FFB300;
		color: white;
		margin: 0 200rpx 0 200rpx;
	}


	.radio {
		margin: 0 0 5rpx 600rpx;
	}
</style>
